import json
import logging
import traceback
from datetime import datetime
from django.db import transaction
from django.http import JsonResponse
from rest_framework import status
from Model.models import Role as R
from Model.modelsView import RoleInfo
from tools.Tools import check_text, createHandleLog, getCurrentUser

res = dict()
logger_info = logging.getLogger('info')


def Role(request):
    res.clear()
    try:
        if request.method == 'GET':
            return getRole(request)
        elif request.method == 'POST':
            return createRole(request)
        elif request.method == 'PUT':
            return modifyRole(request)
        elif request.method == 'DELETE':
            return delRole(request)
    except Exception as e:
        print(e)
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 200
        res['message'] = '请求错误!'
        return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)


# 获取全部角色
def getRole(request):
    name = request.GET.get('name')
    role = RoleInfo.objects.all()
    if check_text(name):
        role = role.filter(name__contains=name)
    res['status'] = 200
    res['data'] = list(role.values())
    res['message'] = '请求成功'
    return JsonResponse(res, status=status.HTTP_200_OK)


# 新建角色
@transaction.atomic()
def createRole(request):
    body = json.loads(request.body)
    name = body.get('name')
    role = R.objects.create()
    role.role_id = role.id
    role.name = name
    role.save()
    createHandleLog('新增角色', str(getCurrentUser(request)), body)
    logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《新增角色》权限 添加内容 {body}')
    res['status'] = 200
    res['message'] = '新建成功'
    return JsonResponse(res, status=status.HTTP_200_OK)


# 修改角色
@transaction.atomic()
def modifyRole(request):
    body = json.loads(request.body)
    role_id = body.get('role_id')
    name = body.get('name')
    page_auth = body.get('page_auth')
    operation_auth = body.get('operation_auth')
    role = R.objects.get(role_id=role_id)
    if name:
        role.name = name
    if check_text(page_auth):
        role.page_auth = page_auth
    if check_text(operation_auth):
        role.operation_auth = operation_auth
    createHandleLog('修改角色', str(getCurrentUser(request)), body)
    logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《修改角色》权限 修改内容 {body}')
    role.save()
    res['status'] = 200
    res['message'] = '修改成功'
    return JsonResponse(res, status=status.HTTP_200_OK)


# 删除角色
@transaction.atomic()
def delRole(request):
    role_id = request.GET.get('role_id')
    role = R.objects.get(role_id=role_id)
    createHandleLog('删除角色', str(getCurrentUser(request)), role.name)
    logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《删除角色》权限 删除角色 {role.name}')
    role.delete()
    res['status'] = 200
    res['message'] = '删除成功'
    return JsonResponse(res, status=status.HTTP_200_OK)
